# coding: utf-8

import datetime

from flask_wtf import FlaskForm
from wtforms import widgets, RadioField
from wtforms.fields.html5 import DateField
from wtforms_components import SelectField, SelectMultipleField
from wtforms_components import DateTimeField

NotChoices = [(-1, ' ')]


class WphForm(FlaskForm):
    """
    add by zhouhl 2018-04-16
    项目Form基类
    """

    def generate_kwargs(
        self,
        ignore_keys=('submit',),
        ignore_values=(None, '', False)
    ):
        """
        返回 query_kwargs 供 view 查询使用
        返回 url_kwargs 供 view 渲染分页url使用
        """

        # NOTE by chenhj at 2018-5-8, 这里用str去判断,
        #  否则传入的value为0时, 会出现0 == False为True的情况, 导致0无法过滤
        ignore_values = tuple(map(lambda x: str(x), ignore_values))
        query_kwargs, url_kwargs = {}, {}
        for key, value in self.data.items():
            tmp_form_field = getattr(self, key)
            # 排除ignore_keys
            # 排除未设置的form字段，value可能为0
            # 排除为值为 NotChoices 的 NonValidatingSelectField

            # NOTE by zhouhl
            # 理论上应该初始化时设置 wtforms.BooleanField 的 false_values 为 ('false', '', False)。
            # 这里使用 false_values 的 默认值('false', '')，同时将False的值直接过滤，防止在url错误渲染
            if key in ignore_keys or str(value) in ignore_values:
                continue
            if isinstance(tmp_form_field, NonValidatingSelectField) \
                    and str(value) == str(NotChoices[0][0]):
                continue

            query_kwargs[key] = value
            # NOTE 由于数据库使用时间戳，前端显示用ISO格式导致的临时解决方案
            if isinstance(tmp_form_field, MyDateTimeField):
                url_kwargs[key] = tmp_form_field.raw_data[0]
            else:
                url_kwargs[key] = value

        return query_kwargs, url_kwargs


def change_datetime2timestamp(obj):
    """
    转换datetime对象为timestamp
    """
    return int(datetime.datetime.timestamp(obj))


class NonValidatingSelectField(SelectField):
    def pre_validate(self, form):
        pass


class NonValidatingDateField(DateField):
    def pre_validate(self, form):
        pass


class NonValidatingSelectMultipleField(SelectMultipleField):
    def pre_validate(self, form):
        pass


class MultiCheckboxField(SelectMultipleField):
    widget = widgets.ListWidget(prefix_label=False)
    option_widget = widgets.CheckboxInput()


class NonValidatingMultiCheckboxField(MultiCheckboxField):
    def pre_validate(self, form):
        pass


class NonValidatingRadioField(RadioField):
    def pre_validate(self, form):
        pass


class MyDateTimeField(DateTimeField):
    """
    接受datetime，最后给出timestamp
    """
    def process_formdata(self, valuelist):
        """
        仿造wtforms.DateField的process_formdata实现
        """
        super(MyDateTimeField, self).process_formdata(valuelist)
        if self.data is not None:
            self.data = change_datetime2timestamp(self.data)
        else:
            self.data = None
